// pages/newvote/newvote.js
let app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
 
    already: !0,
    selectSum: 0,
    removed: !1,
    voteSum: 0,
    comments: [],
    maxTimeTick: null,
    daily:false,
    voteType: "detail",
    _id: '',
    vid:'',
    showAvatar:'',
    userId:'',
    admin:'',
    templateOptions:'',
    pushData2:{topicTitle:'12345为ID复古风阿迪就会功夫的老地方还看见对方i 老地方 地方地方地方领导说了无人管温柔哈哈 哈哈',nickName:'name',content:'content',dayOnce:true,sumDeadline:1200,userSum:880,subscribeCount:123,voteRates:[50,20],selectList:[1,2],files:[{src:123}],options:[{content:1,open:true},{content:2},{content:5}]},
    canPush: true,
    showData2:{voteRates:['可以','不可以'],options:[1,23,4]},
    voteInfo:{},
    pushData:{},
    selectList:[],
    showData:[],
    group_count:0,
    maxSelectCount:1,
    nickName:'tusm',
    showLogin:true,
    has_check:0,
    v_img:'',
    has_answer:false,
    default_img:'http://bmobfile.funnyfish.cn/2020/05/11/16555bbe40b88c158056807e57232761.png',
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var vid=options.tid;
    if(!vid){
      wx.showToast({
        title:'不存在',
        icon:'none'
      })
      return;
    }
    // var vid='2767a23987'
    var uid=wx.getStorageSync('uid')
    this.setData({
      vid:vid
    })
    this.getVoteInfo(vid)
    this.getMyAn(uid,vid)
  },
  getinfo(e){
  console.log(e);
  console.log("====")
 

  console.log(e.detail.errMsg)
  let that=this;
  var uid=wx.getStorageSync('uid')
  if (uid&&e.detail.userInfo) {
    console.log("tiaozhuan1")
    let userInfo = e.detail.userInfo
    let username = userInfo.nickName

    let sex = userInfo.gender
    let uimg = userInfo.avatarUrl
  
  
    wx.setStorageSync('sex', sex)
    wx.setStorageSync('myname', username)
    wx.setStorageSync('nickName', username);
    wx.setStorageSync('uimg', uimg)
    wx.setStorageSync('myurl', uimg)
    console.log("tiaozhuan3")
    //this.updateUser(uid,sex,uimg,username)
    this.setData({
      showLogin:false
    })
 
  
  

  }
},
tochart(e){
  console.log("eee=")
  console.log(e)
  var tid=this.data.vid
  if(!tid){
    return
  }
  qq.navigateTo({
    url:'chart?tid='+tid
  })
},
  updateUser(uid,sex,uimg,username){
    var param = {
      'id': uid,
      'sex': sex,
      'avatarurl': uimg,
      'nickName':username
    }
    wx.Als.bmobFunc('vote_user', 'update', param).then(res => {
      
      if (res) {
    
       
      }
    })
  },
  update_vote(vid,form,addnum){
    var aid=wx.getStorageSync('uid')
    let query = wx.Bmob.Query('vote_info');
    const pointer = wx.Bmob.Pointer('vote_answer')
    const relID = pointer.set(aid)
    // content=Number(content)
    // const relation = wx.Bmob.Relation('vote_answer') // 需要关联的表
    // const relID = relation.add([aid,"vid"]) 
    query.get(vid).then(res => {
      console.log(res)
      console.log("udpate")
      let num2=addnum+Number(res.group_count);
      // let num2=Number(res.group_count)+addnum;
      
     res.set('form',form);
     res.set('group_count',num2);
     res.set('newid',relID); 
       res.save();
    
    }).catch(err => {
      console.log(err)
    })
        },

        updateDate(vid,addnum,nowday){
           var that = this;

    //e='06ba749f36'
     let param = {
        vid: vid,
        date:nowday.toString()
      }

      var attr = {
        limit:1
      }


      wx.Als.bmobFunc('vote_date', 'all', param, attr).then(ret => {
          let res=ret[0]
          if(ret[0]&&res){
            let param3={
              id:res.objectId,
              num:addnum,
              field:'num'
            }
  wx.Als.bmobFunc('vote_date','inc',param3).then(res=>{
              console.log(res)
            })
          }else{
            let param2={
              vid:vid,
              date:nowday,
              num:addnum
            }
            wx.Als.bmobFunc('vote_date','add',param2).then(res=>{
              console.log(res)
            })
          }

      })

        },
  getVoteInfo: function(e) {
    var that = this;

    //e='06ba749f36'
     let param = {
        objectId: e,
       
      }

      var attr = {
        limit:1
      }


      wx.Als.bmobFunc('vote_info', 'all', param, attr).then(ret => {
        console.log(ret);

      let res=ret[0]
      if(res&&ret[0]){
        var selectList=res.form.votearr.opts.map(item=>{
          return '';
        })
   
       that.setData({
           pushData:res.form,
           selectList:selectList,
           showData:res.form.votearr.opts,
           nickName:res.nickName,
           v_img:res.uimg,
           daily:res.form.daily,
           maxSelectCount:res.form.most?res.form.most:1,
           group_count:res.group_count||0
       })
       
      }
       


      }).catch(err => {
        console.log(err)
      })
},
getMyAn(uid,vid){
  let that=this;
        let param={
            uid:uid,
            vid:vid
        }
        let attr={
            limit:1,
          
        }  
        wx.Als.bmobFunc("vote_detail", 'all',param,attr).then(res => {
            if(res&&res[0]){
               
               that.setData({
                   has_answer:true,
                   selectList:res[0].selectList
               })
            }

        })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  submit(e){
    var that=this
    var vid=this.data.vid
    if(this.data.pushData.close){
          wx.showToast({
        title: '投票结束',
        icon:'none'
      })
      return
    }
    var has_check=this.data.has_check
    if(!has_check){
      wx.showToast({
        title: '请选择选项',
        icon:'none'
      })
      return
    }
    var selectList=this.data.selectList
    var form=this.data.pushData;
    var addnum=0;
    var showData=this.data.showData
    selectList.forEach((item,key)=>{
      if(item){
        console.log("key")
        console.log(key)
        addnum=addnum+1;
        form.votearr.opts[key].num=form.votearr.opts[key].num+1;
     
      }
    })

    // this.setData({
    //   showData:form.votearr.opts,
    //   group_count:this.data.group_count+addnum,
    //   pushData:form,
    //   has_answer:true
    // })
    this.add_vote(vid,selectList,form,addnum)
  },
  gohome(){
    wx.switchTab({
      url: '../../pages/index/index',
    })
    // wx.redirectTo({
    //   url: 'pages/index/index',
    // })
  },
  onOptionItem: function(t) {

    if(this.data.has_answer&&!this.data.daily){
      return;
    }
  
    var e = t.currentTarget.dataset.current;
    var s=this.data.selectList;
   var maxSelectCount=this.data.maxSelectCount
   var newinfo=!s[e];
     console.log("--2-")
   var newarr=[]
   if(!s[e]){
  var newarr=s.filter(item=>{
    return item===true;
  })
}
  var info='selectList['+e+']';
 
  if(newarr.length>=maxSelectCount){
    wx.showToast({
      title: "最多选择" + maxSelectCount + "项",
          icon: "none"
    })
    this.setData({
      [info]:false
    })
    return;
  }

    this.setData({
      [info]:newinfo,
      has_check:newarr.length?newarr.length:1
    })
  
},

add_vote(vid,selectList=[],form,addnum=1,type=2){
  let a=this;
  var uid=wx.getStorageSync('uid')
  var vid=this.data.vid
  var group_count=this.data.group_count
  var param2={
    uid:uid,
    vid:vid
  }
 
  var attr={
    limit:1
}

 if(this.data.daily){
    console.log("日投")
     var today = new Date()
      
  　　var tYear = today.getFullYear();
   
  　　var tMonth = today.getMonth()+1;
   
  　　var tDate = today.getDate();

      if(tMonth.toString().length == 1){
        　　　　tMonth = "0" + tMonth;
    　　}
    if(tDate.toString().length == 1){
   
      　　　　　tDate = "0" + 　tDate;
   
  　　}
    var nowday=tYear+'-'+tMonth+'-'+tDate;
    var day=nowday+' 00:00:00';
    attr.bigfield={
      k:'createdAt',
      v:day
    }
   // param2.daily=;
  }

       //a.updateDate(vid,addnum,nowday)
  wx.Als.bmobFunc('vote_detail','all',param2,attr).then(res=>{
      console.log(res)
            if(res.length==0&&res){
              const pointer = wx.Bmob.Pointer('vote_user')
              const poiID = pointer.set(uid)
              var uimg=wx.getStorageSync('uimg')
              var nickName=wx.getStorageSync('nickName')
              let param={
                  uid:uid,
                  vid:vid,
                  selectList:selectList,
                  userinfo:poiID,
                  uimg:uimg,
                  nickName:nickName,
                  type:type
              }
              wx.Als.bmobFunc('vote_detail', 'add', param).then(res => {
                 console.log(res)
                 if(res){
                   wx.showToast({
                     title: '提交成功',
                   })
                 }
                })
              a.setData({
                has_answer:true,
                pushData:form,
                showData:form.votearr.opts,
                group_count:group_count+addnum,
               
              })
              a.update_vote(vid,form,addnum);
              a.updateDate(vid,addnum,nowday)
            }else{
              wx.showToast({
                title: '已经回答',
                icon:'none'
              })
            } 
  })


},

clearSelect: function() {
  console.log("aa")
 // for (var t = 0; t < this.data.selectList.length; t++) this.data.selectList[t] = !1;
  // this.data.pushData.selectSum = 0, this.setData({
  //     pushData: this.data.pushData
  // });
},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var uimg=wx.getStorageSync('uimg')
    var nickName=wx.getStorageSync('nickName')
    if(uimg&&nickName){
      this.setData({
        showLogin:false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(t) {
    var e = wx.getStorageSync("nickName")
     var uid = wx.getStorageSync("uid");
          if("button" === t.from){
            var a = t.target.dataset.voteid, o = e || "朋友";
    return "button" === t.from && console.log(t), {
        title: o + "邀你投一票！",
        path: "/more/newvote/detail?shareFrom=share&nickname=" + e + "&tid=" + a+"&uid="+uid,
        success: function(t) {}
    };
          }else{
               return {
        title:  "邀你投票！热门话题讨论~",
            path: "/pages/index/index",
            success: function(t) {}
        };
          }
},
})